package endoscopic

import (
	"rongyy/src/app"
	"rongyy/src/middlewares"
	"rongyy/src/models"
)

type SendMsgHistory struct {
	models.BaseModel `xorm:"extends"`
	TemplateId       int64        `xorm:"template_id" json:"template_id"`
	IsConfirm        int          `xorm:"is_confirm" json:"is_confirm"`
	PatientId        string       `xorm:"patient_id" json:"patient_id"`
	Openid           string       `xorm:"open_id" json:"open_id"`
	TemplateInfo     *MsgTemplate `xorm:"-" json:"template_info"`
}

func (pm *SendMsgHistory) TableName() string {
	return "send_msg_history"
}

func (pm *SendMsgHistory) Insert() error {
	_, err := app.DB().Insert(pm)
	if err != nil {
		middlewares.Logger.Println("ERROR - FollowUp Insert failed ", err)
		return err
	}
	return nil
}

func (pm *SendMsgHistory) SelectByPT(pid string, tid int64) (*SendMsgHistory, error) {
	am := &SendMsgHistory{}
	has, err := app.DB().Where("patient_id = ? and template_id=?", pid, tid).Limit(1).Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return am, nil
}

func (pm *SendMsgHistory) Update(req *SendMsgHistory) error {
	_, err := app.DB().ID(req.Id).Cols("is_confirm").Update(req)
	if err != nil {
		middlewares.Logger.Println("ERROR - type Update failed ", err)
		return err
	}
	return nil
}

func (pm *SendMsgHistory) SelectById(id int64) (*SendMsgHistory, error) {
	am := &SendMsgHistory{}
	has, err := app.DB().Where("id = ? ", id).Limit(1).Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return am, nil
}

func (pm *SendMsgHistory) SelectByList(limit int, start int) ([]SendMsgHistory, int64, error) {
	data := make([]SendMsgHistory, 0)
	s := app.DB().Table("set_msg_history")
	total, err := s.Limit(limit, limit*start).Desc("created_at").FindAndCount(&data)
	if err != nil {
		return nil, 0, err
	}
	return data, total, nil
}
